import cgi
import datetime
import urllib
import webapp2

import jinja2
import os
import copy

dir = os.path.dirname(__file__)
filename = os.path.join(dir, '../view')
jinja_environment = jinja2.Environment(loader=jinja2.FileSystemLoader(filename))

from google.appengine.ext import db
from model.Person import Person

guyprefers = {long:[long]}
galprefers = {long:[long]}

def create_person(fid, gndr, srch, rnk):
    obj = Person(fb_uid=fid, gender=gndr, searching=srch)
    obj.ranking = rnk
    obj.put()
	
def matchmaker():
    guys = sorted(guyprefers.keys())
    gals = sorted(galprefers.keys())
    guysfree = guys[:]
    engaged  = {}
    guyprefers2 = copy.deepcopy(guyprefers)
    galprefers2 = copy.deepcopy(galprefers)
    while guysfree:
        guy = guysfree.pop(0)
        guyslist = guyprefers2[guy]
        interested = False
        while guyslist:
            gal = guyslist.pop(0)    
            if galprefers[gal].count(guy) > 0:
                interested = True
                break
        if not interested:
            continue

        fiance = engaged.get(gal)
        if not fiance:
            # She's free and is interested in this "guy"
            engaged[gal] = guy
        else:
            # The bounder proposes to an engaged lass!
            galslist = galprefers2[gal]
            if galslist.count(guy)>0 and galslist.index(fiance) > galslist.index(guy):
                # She prefers new guy
                engaged[gal] = guy
                if guyprefers2[fiance]:
                    # Ex has more girls to try
                    guysfree.append(fiance)
            else:
                # She is faithful to old fiance
                if guyslist:
                    # Look again
                    guysfree.append(guy)
    return engaged
	

class SMAlgorithm(webapp2.RequestHandler):
    def get(self):
	
        #Prueba
        #NO DESCOMENTAR: se llena la base de datos de valores repetidos
        #Create males
        create_person(1,'male','female', [5,6,7,8])
        create_person(2,'male','female', [5,6,7,8])
        create_person(3,'male','female', [5,6,7,8])
        create_person(4,'male','female', [5,6,7,8])        

		# #create females
        create_person(5,'female','male', [1,2,3,4])
        create_person(6,'female','male', [1,2,3,4])
        create_person(7,'female','male', [1,2,3,4])
        create_person(8,'female','male', [1,2,3,4])


		#fin de prueba

        # m1 = Person(fb_uid=1, gender='male', searching='female')
        # m2 = Person(fb_uid=2, gender='male', searching='female')
        # m3 = Person(fb_uid=3, gender='male', searching='female')

        # w1 = Person(fb_uid=4, gender='female', searching='male')
        # w2 = Person(fb_uid=5, gender='female', searching='male')
        # w3 = Person(fb_uid=6, gender='female', searching='male')

        # w1.put()
        # w2.put()
        # w3.put()

        # m1.ranking = [w1.fb_uid, w2.key(), w3.key()]
        # m2.ranking = [w1.key(), w2.key(), w3.key()]
        # m3.ranking = [w1.key(), w2.key(), w3.key()]

        # m1.put()
        # m2.put()
        # m3.put()

        # w1.ranking = [m1.key(), m2.key(), m3.key()]
        # w2.ranking = [m1.key(), m2.key(), m3.key()]
        # w3.ranking = [m1.key(), m2.key(), m3.key()]

        # w1.put()
        # w2.put()
        # w3.put()

#		Si no esta registrado, lo mando a la pantalla inicial
		
#		Si esta registrado, lo mando a otro lugar (aun no hecho).
        
        #current_user = db.GqlQuery("SELECT * FROM User WHERE fb_uid IN :1", current_fb_uid)    	
        #obtengo toda la gente que esta en el match
        people_query = Person.all()
		
        people = people_query.fetch(15)

        males = []
        females = []
        for person in people:
            if person.gender == 'male':
                males.append(person)
            else:
                females.append(person)

        for male in males:
            guyprefers[male.fb_uid] = male.ranking
		
        for female in females:
            galprefers[female.fb_uid] = female.ranking
		
        engaged = matchmaker()
		
        # mandar la gente por parametro de la pagina
        template_values = {
        	'people': people,
            'engaged': engaged,
        }

        template = jinja_environment.get_template('resultSM.html')
        self.response.out.write(template.render(template_values))
